package org.budo.dubbo.protocol.async.repository;

import org.budo.dubbo.protocol.async.util.RepositoryUtil;
import org.budo.support.lang.util.StringUtil;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.alibaba.dubbo.rpc.Exporter;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
public abstract class AbstractAsyncRepository implements AsyncRepository, //
        ApplicationContextAware, //
        BeanNameAware, //
        DisposableBean {

    public ApplicationContext applicationContext;

    /**
     * 空闲拉取休息时间，单位秒
     */
    private Integer popIdleSeconds = 1;

    private String beanName;

    /**
     * 将message序列化后发送
     */
    public abstract void sendMessage(String destinationName, Object message);

    /**
     * 传入序列化后的消息,String或bytes
     */
    public abstract void sendRawMessage(String destinationName, Object rawMessage);

    public Integer popMessage(Exporter<?> exporter) {
        String asyncRepositoryBeanName = RepositoryUtil.getAsyncRepositoryBeanName(exporter.getInvoker());

        if (!StringUtil.equals(asyncRepositoryBeanName, this.getBeanName())) { // 只处理指定当前Bean的
            if (log.isDebugEnabled()) {
                log.debug("#175 asyncRepositoryBeanName=" + asyncRepositoryBeanName + ", this=" + this);
            }

            return 0;
        }

        // RpcContext.getContext().getUrl(); // 可用这个方法获取 destinationName
        Integer messageCount = this.popMessageAndInvoke(exporter.getInvoker());

        if (log.isDebugEnabled()) {
            log.debug("#136 dubboProtocolPopMessage, dubboExporter=" + exporter + ", " + "messageCount=" + messageCount);
        }

        return messageCount;
    }
}